package com.qxzn.module.im.model;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.api.greendao.bean.ChatMsgBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.LeaveVoiceMsgBean;
import com.qxzn.app.bean.MsgBean;
import com.qxzn.app.bean.SendMsgSuccessBean;
import com.qxzn.app.page.util.face.FileUtil;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.im.interfaces.MsgInterface;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MsgModel {

    private Context context;
    private MsgInterface.OnSendMsgListener msgListener;
    private MsgInterface.OnGetMsgListListener getMsgListListener;
    private MsgInterface.OnGetMsgListener getMsgListener;
    private MsgInterface.OnGetUnreadLeaveMsgListListener getUnreadMsgListener;
    private MsgInterface.OnUpdateUnreadLeaveMsgListListener updateUnreadMsgListListener;

    public MsgModel(Context context) {
        this.context = context;
    }

    public void sendMsg(final long insertId, ChatMsgBean bean) {
        if (TextUtils.isEmpty(bean.getFilePath())) {
            return;
        }
        MultipartBody.Part fileBody = HttpRequest.getPartFileBody(new File(bean.getFilePath()));
        RequestBody device_id = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(context));
        RequestBody username = HttpRequest.getPartBody(bean.getSender());
//        RequestBody words = HttpRequest.getPartBody("萨迪克九分裤");
        RequestBody timelength = HttpRequest.getPartBody(bean.getFileDuration() + "");
//        RequestBody createtime = HttpRequest.getPartBody(System.currentTimeMillis() + "");
        RequestBody messagetype = HttpRequest.getPartBody(bean.getMsgType() + "");//消息类型 1文本 2语音 3图片
//        RequestBody state = HttpRequest.getPartBody("0");//是否已读 0未读 1已读
//        RequestBody recipient = HttpRequest.getPartBody(SharePreferenceUtil.getDeviceId(context));
        RequestBody recipient = HttpRequest.getPartBody(bean.getReceiver());
        HttpRequest.getService().sendMsg(device_id, username, timelength, messagetype, recipient, fileBody).enqueue(new Callback<BaseBean<SendMsgSuccessBean>>() {
            @Override
            public void onResponse(Call<BaseBean<SendMsgSuccessBean>> call, Response<BaseBean<SendMsgSuccessBean>> response) {
                BaseBean<SendMsgSuccessBean> baseBean = response.body();
                if (baseBean == null || baseBean.getCode() != 200) {
                    AppUtil.showToast(context, "发送失败");
                }
                if (msgListener != null) {
                    msgListener.onSuccess(insertId, baseBean);
                }
            }

            @Override
            public void onFailure(Call<BaseBean<SendMsgSuccessBean>> call, Throwable t) {
                if (msgListener != null) {
                    msgListener.onFailure(insertId);
                }
                AppUtil.showToast(context, "网络错误，请稍后再试！");
            }
        });
    }

    public void getMsgList(int page, int pageSize, String receiver) {
        JSONObject params = new JSONObject();
        params.put("device_id", SharePreferenceUtil.getDeviceId(context));
        params.put("username", SharePreferenceUtil.getUserName(context));
//        params.put("words", "萨迪克九分裤");
        params.put("recipient", receiver);
        params.put("current_page", page);
        params.put("num", pageSize);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
        HttpRequest.getService().getVoiceMsgList(body).enqueue(new Callback<BaseBean<MsgBean>>() {
            @Override
            public void onResponse(Call<BaseBean<MsgBean>> call, Response<BaseBean<MsgBean>> response) {
                BaseBean<MsgBean> baseBean = response.body();
                if (getMsgListListener != null) {
                    getMsgListListener.onSuccess(baseBean);
                }
                if (baseBean == null || baseBean.getCode() != 200) {
                    AppUtil.showToast(context, "获取聊天记录失败");
                }
            }

            @Override
            public void onFailure(Call<BaseBean<MsgBean>> call, Throwable t) {
                AppUtil.showLog("异常：" + t.getMessage());
                AppUtil.showToast(context, "网络错误，请稍后再试！");
                if (getMsgListListener != null) {
                    getMsgListListener.onFailure();
                }
            }
        });
    }

    public void getMsgById(String msgId) {
        JSONObject params = new JSONObject();
        params.put("id", msgId);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
        HttpRequest.getService().getMsgById(body).enqueue(new Callback<BaseBean<MsgBean.ResultBean>>() {
            @Override
            public void onResponse(Call<BaseBean<MsgBean.ResultBean>> call, Response<BaseBean<MsgBean.ResultBean>> response) {
                BaseBean<MsgBean.ResultBean> baseBean = response.body();
                if (baseBean != null && baseBean.getCode() == 200) {
                    if (getMsgListener != null) {
                        getMsgListener.onSuccess(baseBean);
                    }
                }
//                if (baseBean == null || baseBean.getCode() != 200) {
//                    AppUtil.showToast(context, "获取聊天记录失败");
//                }
            }

            @Override
            public void onFailure(Call<BaseBean<MsgBean.ResultBean>> call, Throwable t) {
                AppUtil.showToast(context, "网络错误似乎有点问题！");
//                if (getMsgListener != null) {
//                    getMsgListener.onFailure();
//                }
            }
        });
    }

    public void getUnreadLeaveMsg(int page, int pageSize) {
        JSONObject params = new JSONObject();
        params.put("current_page", page);
        params.put("num", pageSize);
        params.put("device_id", SharePreferenceUtil.getDeviceId(context));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
        HttpRequest.getService().getUnreadLeaveMsg(body).enqueue(new Callback<BaseBean<LeaveVoiceMsgBean>>() {
            @Override
            public void onResponse(Call<BaseBean<LeaveVoiceMsgBean>> call, Response<BaseBean<LeaveVoiceMsgBean>> response) {
                if (getUnreadMsgListener != null) {
                    getUnreadMsgListener.onGetUnreadLeaveMsgListSuccess(response.body());
                }
            }

            @Override
            public void onFailure(Call<BaseBean<LeaveVoiceMsgBean>> call, Throwable t) {
                AppUtil.showToast(context, "网络错误似乎有点问题！");
                if (getUnreadMsgListener != null) {
                    getUnreadMsgListener.onGetUnreadLeaveMsgListFailure();
                }
            }
        });
    }

    public void updateUnreadLeaveMsg(String msgId) {
        JSONObject params = new JSONObject();
        params.put("id", msgId);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
        HttpRequest.getService().updateUnreadLeaveMsg(body).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                if (updateUnreadMsgListListener != null) {
                    updateUnreadMsgListListener.onUpdateUnreadLeaveMsgListSuccess(response.body());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(context, "网络错误似乎有点问题！");
                if (updateUnreadMsgListListener != null) {
                    updateUnreadMsgListListener.onUpdateUnreadLeaveMsgListFailure();
                }
            }
        });
    }

    public void setSendMsgListener(MsgInterface.OnSendMsgListener msgListener) {
        this.msgListener = msgListener;
    }

    public void setGetMsgListListener(MsgInterface.OnGetMsgListListener getMsgListListener) {
        this.getMsgListListener = getMsgListListener;
    }

    public void setGetMsgListener(MsgInterface.OnGetMsgListener getMsgListener) {
        this.getMsgListener = getMsgListener;
    }

    public void removeListener() {
        msgListener = null;
        getMsgListListener = null;
        getMsgListener = null;
        getUnreadMsgListener = null;
        updateUnreadMsgListListener = null;
    }

    public void setGetUnreadMsgListener(MsgInterface.OnGetUnreadLeaveMsgListListener getUnreadMsgListener) {
        this.getUnreadMsgListener = getUnreadMsgListener;
    }

    public void setUpdateUnreadMsgListListener(MsgInterface.OnUpdateUnreadLeaveMsgListListener updateUnreadMsgListListener) {
        this.updateUnreadMsgListListener = updateUnreadMsgListListener;
    }
}
